from sqlalchemy import *
from core.db import *
from core import *
import re
from servers.root.definitions import *
from pickle import dumps,loads

class qAyeRootIndex(object):
	pass

aye_root_index_table = Table('aye_root_index_table',metadata,
		Column('aye_id',Integer,ForeignKey("aye_table.id"),primary_key=True),
		Column('index_dump',String))

aye_root_index_mapper = mapper(qAyeRootIndex,aye_root_index_table,properties={
	'aye' : relation(qpath.qAye,backref=backref('root_index',uselist=False))})
aye_root_index_query = session.query(qAyeRootIndex)


def isSupportQuery(query,domain):
	pass
	
def filter(query,domain):
	pass

qpath.server_isSupports.append(isSupportQuery)
qpath.server_filter.append(filter)




def cartesian(dic1,dic2):
	result = 0;
	for x in dic1.keys():
		if x in dic2:
			result = result + dic1[x]*dic2[x]
	return result		

def delStopRoots(root_index):
	stopRoots = [23,26,34,44,66,81,165,176,187,209,221,232,243,266,286,349,363,444,495,515,521,520,569,570,575,578,581,586,592,596,597,652,671,675,693,694,818,819,843,844,857,862,871,873,874,882,890,980,981,1042,1061,1062,1063,1124,1136,1146,1182,1427,1446,1447,1448,1449,1457,1464,1509,1552,1613,1628,1660,1694,1704,1802,1813,1814,1824,1835,1845]
	for sr in stopRoots:
		if sr in root_index:
			root_index[sr] = 0
	return root_index		


def findSimilarAyat(iaye=None,index_dic=None):
	result = {}
	if iaye!=None:
		r = delStopRoots(loads(iaye.root_index.index_dump))
	else:
		print index_dic
		r = delStopRoots(index_dic)
		print r
	for sure in qpath.get("*/"):
		for aye in sure.ayat:
			if aye.root_index != None:
				t = cartesian(loads(aye.root_index.index_dump),r)
				if t not in result:
					result[t] = []
				result[t].append(aye)
	return result

def index_ayat(qp="*/"):
	
	for sure in qpath.get(qp):
		for aye in sure.ayat:
			root_index = {}
			for word in aye.words:
				for root in word.roots:
					if root.root.id in root_index:
						root_index[root.root.id] = root_index[root.root.id] + 1.0/len(word.roots)
					else:
						root_index[root.root.id] = 1.0/len(word.roots)
			aye.root_index = qAyeRootIndex()
			aye.root_index.index_dump = dumps(root_index)
			session.flush()
			print "%d:%d" % (aye.id,len(root_index))

if __name__ == "__main__":
	pass
